﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Beginning.Api.Application.Command.ChangeHouse;
using RearLivestock.Common.Domains.hhx;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.PigDeath
{
    public class QueryPigDeathHandler : IRequestHandler<QueryPigDeathCommand, Result<PageResultDto<PigDeathDto>>>
    {
        /// <summary>
        /// 猪只死亡仓储
        /// </summary>
        private readonly IBaseRepository<PigDeaths> pigDeathsRepository;
        /// <summary>
        /// 栋舍信息仓储
        /// </summary>
        private readonly IBaseRepository<Bedrooms> bedroomsRepository;
        /// <summary>
        ///  栏位仓储
        /// </summary>
        private readonly IBaseRepository<Fields> fieldsRepository;
        /// <summary>
        /// 基本信息耳号仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> basicInformationRepository;
        /// <summary>
        /// 死亡原因仓储
        /// </summary>
        private readonly IBaseRepository<DeathReasons> deathReasonsRepository;
        /// <summary>
        /// 品种
        /// </summary>
        private readonly IBaseRepository<Varieties> varietiesRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="pigDeathsRepository"></param>
        /// <param name="bedroomTypesRepository"></param>
        /// <param name="basicInformationRepository"></param>
        /// <param name="deathReasonsRepository"></param>
        /// <param name="varietiesRepository"></param>
        public QueryPigDeathHandler(IBaseRepository<PigDeaths> pigDeathsRepository, IBaseRepository<Bedrooms> bedroomsRepository, IBaseRepository<Fields> fieldsRepository, IBaseRepository<BasicInformation> basicInformationRepository, IBaseRepository<DeathReasons> deathReasonsRepository, IBaseRepository<Varieties> varietiesRepository)
        {
            this.pigDeathsRepository = pigDeathsRepository;
            this.bedroomsRepository = bedroomsRepository;
            this.fieldsRepository = fieldsRepository;
            this.basicInformationRepository = basicInformationRepository;
            this.deathReasonsRepository = deathReasonsRepository;
            this.varietiesRepository = varietiesRepository;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<PigDeathDto>>> Handle(QueryPigDeathCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<PigDeathDto>>() { Code = (int)CommonErrorCode.Search, Data = new PageResultDto<PigDeathDto>() };
            var page = new PageResultDto<PigDeathDto>() { TotalCount = 0, PageCount = 0, List = new List<PigDeathDto>() };
            try
            {
                var list = await (from a in (await pigDeathsRepository.GetAll())
                                  join c in (await basicInformationRepository.GetAll())
                                  on a.BasicInforId equals c.BasicInforId
                                  join d in (await deathReasonsRepository.GetAll())
                                  on a.DeathReasonsId equals d.DeathReasonsId
                                  where a.IsPigDeath ==0
                                  select new PigDeathDto()
                                  {
                                      PigDeathId = a.PigDeathId,
                                      PigDeathDate = a.PigDeathDate,
                                      BasicInforId = a.BasicInforId,
                                      DeathReasonId = a.DeathReasonsId,
                                      Gender = c.Gender,
                                      VarietyName=a.VarietyName,
                                      TurnBuilding =a.TurnBuilding,
                                      TurnColumn=a.TurnColumn,
                                      EarNumber = c.EarNumber,
                                      BirthDate = c.BirthDate,
                                      DeathReasonsName = d.DeathReasonsName,
                                      CreatedOwner = a.CreatedOwner,
                                      CreatedTime = a.CreatedTime,
                                      UpdateOwner = a.UpdateOwner,
                                      UpdateTime = a.UpdateTime,
                                      ExamineOwner = a.ExamineOwner,
                                      ExamineTime = a.ExamineTime,
                                  }).ToListAsync();
                //耳号查询
                if (request.BasicInforId != 0)
                {
                    list = list.Where(d => d.BasicInforId == request.BasicInforId).ToList();
                }
                //死亡原因查询
                if (request.DeathReasonId != 0)
                {
                    list = list.Where(d => d.DeathReasonId == request.DeathReasonId).ToList();
                }
                //总条数
                page.TotalCount = list.Count();
                page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.pageSize);
                page.List = list.OrderBy(d => d.PigDeathId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
                result.Data = page;
                result.Code = (int)CommonErrorCode.Success;
            }
            catch (Exception)
            {
                result.Msg = "猪只死亡分页列表获取异常";
            }
            return result;
        }
    }
}
